package cn.kgc.config;

import cn.kgc.listener.DeadLetterMessageListener;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author wangyue
 * @version 1.0
 */
@Configuration
@ConditionalOnProperty(value = "mq.enableHandleDlx")
public class RabbitDeadLetterConfig {
    @Value("${mq.deadLetterQueueName}")
    private String deadLetterQueueName;
    @Value("${mq.deadLetterExchangeName}")
    private String deadLetterExchangeName;
    @Value("${mq.deadLetterRoutingKey}")
    private String deadLetterRoutingKey;

    /**
     * 配置死信队列
     * @return 死信队列
     */
    @Bean
    public Queue deadQueue(){
        return new Queue(deadLetterQueueName,true,false,false);
    }
    /**
     * 创建死信交换机(路由)
     */
    @Bean
    public DirectExchange deadExchange(){
       return new DirectExchange(deadLetterExchangeName,true,false);
    }
    /**
     * 死信队列和死信交换机进行绑定
     */
    @Bean
    public Binding binding(){
        return BindingBuilder.bind(deadQueue()).to(deadExchange()).with(deadLetterRoutingKey);
    }

    @Bean
    public  SimpleMessageListenerContainer simpleMessageListenerContainer(
            ConnectionFactory connectionFactory,
            DeadLetterMessageListener deadLetterMessageListener
    ){
        SimpleMessageListenerContainer  listenerContainer=new SimpleMessageListenerContainer();
        listenerContainer.setConnectionFactory(connectionFactory);
        listenerContainer.setExposeListenerChannel(true);
        //死信队列的名字
        listenerContainer.setQueueNames(deadLetterQueueName);
        //监听死信队列的监听器
        listenerContainer.setMessageListener(deadLetterMessageListener);
        //信息手动确认
        listenerContainer.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        return listenerContainer;
    }
}